/**
 * 简单的日志工具
 */

const fs = require('fs');
const path = require('path');

// 确保日志目录存在
const logDir = path.join(__dirname, '..', 'logs');
if (!fs.existsSync(logDir)) {
  fs.mkdirSync(logDir, { recursive: true });
}

// 获取当前日期字符串
const getDateString = () => {
  const now = new Date();
  return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`;
};

// 获取当前时间字符串
const getTimeString = () => {
  const now = new Date();
  return `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;
};

// 日志级别
const LogLevel = {
  DEBUG: 'DEBUG',
  INFO: 'INFO',
  WARN: 'WARN',
  ERROR: 'ERROR'
};

/**
 * 写入日志
 * @param {string} level 日志级别
 * @param {string} message 日志消息
 * @param {object} data 附加数据
 */
const log = (level, message, data = null) => {
  const dateStr = getDateString();
  const timeStr = getTimeString();
  const logFile = path.join(logDir, `${dateStr}.log`);
  
  let logMessage = `[${timeStr}] [${level}] ${message}`;
  
  if (data) {
    try {
      logMessage += `\n${JSON.stringify(data, null, 2)}`;
    } catch (err) {
      logMessage += `\n[无法序列化的数据]`;
    }
  }
  
  // 控制台输出
  if (process.env.NODE_ENV === 'development') {
    console.log(logMessage);
  }
  
  // 写入文件
  fs.appendFileSync(logFile, logMessage + '\n');
};

module.exports = {
  LogLevel,
  debug: (message, data) => log(LogLevel.DEBUG, message, data),
  info: (message, data) => log(LogLevel.INFO, message, data),
  warn: (message, data) => log(LogLevel.WARN, message, data),
  error: (message, data) => log(LogLevel.ERROR, message, data)
}; 